package com.lanswon.icc.common.security.component;

import cn.hutool.core.util.StrUtil;
import com.lanswon.icc.common.security.annotation.Inner;
import com.lanswon.icc.common.core.constant.SecurityConstant;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description 服务间接口不鉴权处理逻辑
 * 因为部分内部feign调用 是没有token
 *
 * 例如 定时任务去调用upms的接口 ，所以需在请求头中加了from in的标志 ,upms看到这个from就放行了
 *
 * 外部可能会人工恶意传入 所以网关要给清洗掉
 * @Author zsw
 * @Date 2019/10/30 13:50
 * @Version V1.0
 **/
@Slf4j
@Aspect
@Component
@AllArgsConstructor
public class SecurityInnerAspect implements Ordered {
    private final HttpServletRequest request;

    @SneakyThrows
    @Around("@annotation(inner)")
    public Object around(ProceedingJoinPoint point, Inner inner) {
        String header = request.getHeader(SecurityConstant.FROM);
        if (inner.value() && !StrUtil.equals(SecurityConstant.FROM_IN, header)) {
            log.warn("访问接口 [{}] 没有权限", point.getSignature().getName());
            throw new AccessDeniedException("该接口没有访问权限");
        }
        return point.proceed();
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 1;
    }
}